/*
 * Copyright (c) 2023 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#import "EntryEntryAbilityViewController.h"
#import <libarkui_ios/BridgePlugin.h>
#import "BridgeClass.h"
#import "PublicAlertView.h"
#import "MyPlatformViewFactory.h"
#import "bridgeUtil.h"

@interface EntryEntryAbilityViewController ()<IMessageListener, IMethodResult> {
    NSObject<PlatformViewFactory> *factory;
}

@property (nonatomic, strong) BridgeClass *plugin;
@property (nonatomic, strong) BridgeClass *binary_plugin;
@property (nonatomic, strong) PublicAlertView *publicAlertView;

@end

@implementation EntryEntryAbilityViewController
- (instancetype)initWithInstanceName:(NSString *)instanceName {
    self = [super initWithInstanceName:instanceName];
    if (self) {

    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.extendedLayoutIncludesOpaqueBars = YES;
    [self initBridgePlugin];
    
    factory = [MyPlatformViewFactory alloc];
    // register PlatformViewFactory
    [super registerPlatformViewFactory:factory];
}

// 建立与ArkUI侧同名的平台桥接，即可用于消息传递
- (void)initBridgePlugin {
    BOOL isTaskOption = NO;
    NSString *bridgePluginName = @"TestBridge";
    BridgePluginManager *manager = [self getBridgeManager];
    BridgeType bridgeType = JSON_TYPE;
    TaskOption *option = [[TaskOption alloc] initTaskOption:isTaskOption];
    self.plugin = [[BridgeClass alloc] initBridgePlugin:bridgePluginName bridgeManager:manager bridgeType:bridgeType taskOption:option];
    self.plugin.messageListener = self;
    self.plugin.methodResult = self;
    
    self.binary_plugin = [[BridgeClass alloc] initBridgePlugin:@"Create_Binary_Bridge" bridgeManager:manager bridgeType:BINARY_TYPE];
    self.binary_plugin.messageListener = self;
    self.binary_plugin.methodResult = self;
    
    [bridgeUtil setBridge:self.plugin];
    
}

#pragma mark - IMessageListener ArkUI侧发送的消息代理实现 （注意 BridgePlugin 对象 messageListener 属性添加监听者）
/**
  *  Arkui测调用sendMessage 发送消息到IOS测，将会触发次方法的回调
  *  @param data Arkui 传递过来的数据
  *   return 返回值传递传递给Arkui测
*/
- (id)onMessage:(id)data {
    NSString *bridgeNameStr = @"";
    if ([data isKindOfClass:[NSString class]]) {
        bridgeNameStr = data;
    }
    if ([bridgeNameStr containsString:@"testBridge_NativeToTs_callMethod"]) {
        return @"testBridge_NativeToTs_callMethod success";
    }
    if ([bridgeNameStr containsString:@"Native-ArkUI_ParamMethod"]) {
        MethodData *data = [[MethodData alloc] initMethodWithName:@"testCallBackOfJs" parameter:@[@"信息1"]];
        [self.plugin callMethod:data];
        return @"Native-ArkUI_ParamMethod success";
    }
    if ([bridgeNameStr containsString:@"Native-ArkUI_noParamMethod"]) {
        MethodData *data = [[MethodData alloc] initMethodWithName:@"jsMethod" parameter:@[]];
        [self.plugin callMethod:data];
        return @"Native-ArkUI_noParamMethod success";
    }
    if ([bridgeNameStr containsString:@"testBridge_sendMessage"]) {
        return @"iOS receive success";
    }
    if ([bridgeNameStr containsString:@"estBridge_sendMessageCallBack"]) {
        return @"estBridge_sendMessageCallBack success";
    }
    NSLog(@"Arkui 传递消息给iOS message: %@", data);
    return @"哈哈哈，传入的是这个";
}

/**
 * iOS 通过sendMessage 方法发送消息到Arkui, Arkui成功接到消息后回调此方法传递结果
 * @param data Arkui 返回的信息
*/
- (void)onMessageResponse:(id)data {
    NSLog(@"onMessageResponse：ets返回原生信息:data：%@", data);
    
    
    NSString* dataString = [[NSString alloc] initWithFormat:@"%@",data];
    if ([dataString isEqualToString: @"arkui receive success"]) {
        // 原生sendMessage后返回的数据
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showToast:dataString];
        });
    }
}

- (void)showToast:(NSString*)message {
    UIWindow *window = [[UIApplication sharedApplication].delegate window];
    UIView *toast = [[UIView alloc] initWithFrame:CGRectZero];
    toast.backgroundColor = [UIColor blackColor];
    toast.alpha = 0.6;
    toast.layer.cornerRadius = 5;
    toast.clipsToBounds = YES;
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
    label.text = message;
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont systemFontOfSize:12.0];
    label.textAlignment = NSTextAlignmentCenter;
    
    [toast addSubview:label];
    [window addSubview:toast];
    
    [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        CGRect frame = CGRectMake((window.frame.size.width - 200) / 2,
                                   window.frame.size.height - 100,
                                   200,
                                   50);
        toast.frame = frame;
        label.frame = toast.bounds;
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.5 delay:2.0 options:UIViewAnimationOptionCurveLinear animations:^{
            CGRect frame = CGRectMake((window.frame.size.width - 200) / 2,
                                       window.frame.size.height,
                                       200,
                                       50);
            toast.frame = frame;
        } completion:^(BOOL finished) {
            [toast removeFromSuperview];
        }];
    }];
}

#pragma mark - IMethodResult 用于监听平台侧调用ArkUI侧注册的方法的执行情况
/**
  *  ArkUI侧调用unRegisterMethod方法时将触发该接口，用于通知平台侧事件被注销了。
  *  @param methodName ArkUI侧方法的名称
  *  @param resultValue ResultValue 类 ，并将ArkUI侧方法的返回值传递给平台侧
*/
- (void)onSuccess:(NSString *)methodName resultValue:(id)resultValue {
    NSLog(@"success：ets返回原生信息：%@ ==== %@", methodName, resultValue);
    if ([methodName isEqualToString:@"jsMethod"]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showToast:resultValue];
        });
    }
//    NSString *messageStr = [NSString stringWithFormat:@"%@回调成功TS->Native：%@", methodName, resultValue];
//    dispatch_async(dispatch_get_main_queue(), ^{
//        if (self.publicAlertView) {
//            [self.publicAlertView removeFromSuperview];
//        }
//        self.publicAlertView = [[PublicAlertView alloc] initWithFrame:self.view.frame mainTitle:messageStr];
//        [self.view addSubview:self.publicAlertView];
//        [self.publicAlertView showView];
//    });
//    [self.plugin sendMessage:resultValue];
}

/**
  *  ArkUI侧调用unRegisterMethod方法时将触发该接口，用于通知平台侧事件被注销了。
  *  @param methodName ArkUI侧方法的名称
*/
- (void)onMethodCancel:(NSString *)methodName {
    NSString *messageStr = [NSString stringWithFormat:@"%@ 取消成功", methodName];
    [self.plugin sendMessage:messageStr];
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.publicAlertView) {
            [self.publicAlertView removeFromSuperview];
        }
        self.publicAlertView = [[PublicAlertView alloc] initWithFrame:self.view.frame mainTitle:messageStr];
        [self.view addSubview:self.publicAlertView];
        [self.publicAlertView showView];
    });
    NSLog(@"Cancel：ets返回原生信息：%@", methodName);
}

/**
  *  平台侧调用ArkUI侧定义方法时，如果出错则触发该接口，并将出错信息返回平台侧。具体错误码查看ResultValue类中错误码或者接口文档
  *  @param methodName ArkUI侧方法的名称
  *  @param errorCode 错误码
  *  @param errorMessage 错误信息
*/
- (void)onError:(NSString *)methodName errorCode:(ErrorCode)errorCode errorMessage:(NSString *)errorMessage {
    NSLog(@"error：ets返回原生信息:methodName：%@ ==== errorMessage:%@ ====== errorCode:%d", methodName, errorMessage, errorCode);
}

@end
